<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
 
  include ("../../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  
  //================ XAJAX ================
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Extract form params
    $firmware=$formData["firmware"];
    $id=$firmware["id"];
    $id_phone=$firmware["id_phone"];
    $name=$firmware["name"];
    $description=$firmware["description"];
    $uploadedfile=$formData["uploadedfile"];
    $overwrite=$formData["overwrite"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
		// Check Name ((not null)&&(unique))
    $nameErr=false;
    $fNameArr=array();
  	$res=$asterisk->getProvFirmware(0);
  	if(is_array($res)){
    	foreach($res as $f){
      	if(($f["id"]==$id)||($f["id_phone"]!=$id_phone)) continue;
        $fNameArr[]=trim($f["name"]);
      }
  	} 
    if(trim($name)=="") { 
      //name cannot be null
      $errOut[]= T_("Name cannot be null");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;  
    }else if((is_array($fNameArr))&&(in_array($name,$fNameArr,true))){
      //name must be unique
      $errOut[]= T_("Name already exists. Please change it");
      $objResponse->addAssign("nameErr","innerHTML",$imgErr);
      $nameErr=true;
    }
    if($nameErr===false) $objResponse->addAssign("nameErr","innerHTML","");
    // Check File ((not null)&&(unique))
    $uploadedfileErr=false;
    if((trim($uploadedfile)=="")&&(($id=="")||($overwrite==1))){ 
      //name cannot be null
      $errOut[]= T_("Filename cannot be null");
      $objResponse->addAssign("uploadedfileErr","innerHTML",$imgErr);
      $uploadedfileErr=true;  
    }
    if($uploadedfileErr===false) $objResponse->addAssign("uploadedfileErr","innerHTML","");
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      $script="document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  if(count($_POST)>0){
    //extract request
    $firmware=$_POST["firmware"];
    $entry=Array(
        "id" => $firmware["id"],
        "id_phone" => $firmware["id_phone"],
        "name" => $firmware["name"],
        "description" => $firmware["description"]
      );
    //extract file
    $file_content="";
    if(count($_FILES)>0){
      // File upload check
      if (!is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
				$alert="<div class=\"AlertBad\">".T_("Upload Error: firmware has NOT been edited")."</div>";
        @unlink($_FILES['uploadedfile']['tmp_name']);  
        goToMainPage($alert,"./");
      } 
      // File correctly uploaded
      $handle=fopen($_FILES['uploadedfile']['tmp_name'],"rb");
      $file_content=fread($handle,filesize($_FILES['uploadedfile']['tmp_name']));    
    }
    //put template
    $ret=$asterisk->putProvFirmware($entry,$file_content);
    if($ret>0) $alert="<div class=\"AlertGood\">".T_("Firmware has been successfully edited")."</div>";
    else if($ret==-1) $alert="<div class=\"AlertBad\">".T_("Unable to write file on server: firmware has NOT been edited")."</div>";
    else $alert="<div class=\"AlertBad\">".T_("Firmware has NOT been edited")."</div>";
    //go to main page
    goToMainPage($alert,"../");
  }
    
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getProvFirmware($id);
    if ($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $id_phone=$v["id_phone"];
    $name=$v["name"];
    $description=$v["description"];
    $file_disabled="disabled=\"disabled\"";
    //Title
    $title=sprintf(T_("Edit Template : %1\$s"),$name );
  }else{
    $file_disabled="";
    //Title
    $title=T_("New Template");
  }
  //Prepare Phone opt
  $phoneOpt="";
  $ret=$asterisk->getPhoneType(0);
  if(is_array($ret)){
    foreach($ret as $p) {
      if($p["id"]==$id_phone) $s=" selected=\"selected\" "; else $s="";
      $phoneOpt.="<option value=\"".$p["id"]."\" $s>".$p["vendor"]." ".$p["model"]."</option>\n";
    }
  }
	//set upload limit
  function return_bytes($val) {
    $val = trim($val);
    $last = $val{strlen($val)-1};
    switch($last) {
      case 'k':
      case 'K':
        return (int) $val * 1024;
        break;
      case 'm':
      case 'M':
        return (int) $val * 1048576;
        break;
      default:
        return $val;
    }
  }
  $uploadlimit=min(return_bytes(ini_get("post_max_size")),return_bytes(ini_get("upload_max_filesize")));
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../../admin/lib/xajax/");
  echo $initScript; 
  ?>
    <?$nav="firmware";include("../../navigation.php");?>
    <div class="SectionHeader">
      <div id="loading" style="float: right;"></div>
      <h1><?=$title?></h1>
      <h3><a href="../" class="admin" ><?=T_("Return without save")?></a></h3>
    </div>
    <div id="alert"></div>
    <div id="basic_form">
      <form id="mainform" action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
        <!-- General Info -->
        <h2><?=T_("General Informations")?></h2>
        <p class="blockintro"><?=T_("Template's general informations")?></p>
        <div class="block">
          <dl>
            <dt class="required"><label for="firmware[name]"><?=T_("Name")?>:</label></dt>
            <dd><input type="text" size="25" id="firmware[name]" name="firmware[name]" value="<?=$name?>" /> <span id="nameErr"></span></dd>
            <dt class="required"><label for="firmware[description]"><?=T_("Description")?>:</label></dt>
            <dd><textarea id="firmware[description]" name="firmware[description]" cols="50" ><?=$description?></textarea></dd>
            <dt class="required"><label for="firmware[id_phone]"><?=T_("Phone Type")?>:</label></dt>
            <dd><select id="firmware[id_phone]" name="firmware[id_phone]"><?=$phoneOpt?></select></dd>
            <dt class="required"><label for="firmware[file]"><?=T_("File:")?></label></dt>
            <dd>
            	<input type="file" id="uploadedfile" name="uploadedfile" <?=$file_disabled?> /> <span id="uploadedfileErr"></span>
            	<?if($_GET["id"]!=""){?> <input style="margin-left:30px;" type="checkbox" name="overwrite" value="1" onclick="var fileObj=document.getElementById('uploadedfile'); if(this.checked==true) fileObj.disabled=''; else fileObj.disabled='disabled';" />&nbsp;overwrite <?}?>
            </dd>
            <dt class="required"></dt>
            <dd>&nbsp;&nbsp;(<?=T_("upload limit: ")?><?=$uploadlimit?><?=T_("&nbsp;byte")?>)</dd>
          </dl>
        </div>         
        <!-- Buttons -->
        <div class="action">
          <?if($_GET["id"]!=""){?> <input type="hidden" id="firmware[id]" name="firmware[id]" value="<?=$id?>" /><?}?>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
          <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
        <!--  
          <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>             
          <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
        -->
        </div>
      </form>
    </div>
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="provisioning";include("../../../sidebar.php");?>
      <h1><?=T_("Informations")?></h1>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>

